package com.lancoo.ccas53.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.lancoo.ccas53.aspect.LogAnnotation;
import com.lancoo.ccas53.entity.TaskInfo;
import com.lancoo.ccas53.entity.UserSetting;
import com.lancoo.ccas53.pojo.response.basicPlatform.*;
import com.lancoo.ccas53.pojo.response.score.Retake;
import com.lancoo.ccas53.service.*;
import com.lancoo.ccas53.util.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName YunController
 * @Description TODO
 * @Author quin
 * @Date 2024/5/20 19:31
 */

@Slf4j
@Api(tags = "基础平台相关接口")
@RestController
@RequestMapping("/yun")
public class YunController {
    @Resource
    private YunBasicService yunBasicService;
    @Resource
    private PlanTeachingService planTeachingService;
    @Resource
    private RoomService roomService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private PeriodSchemeService periodSchemeService;
    @Resource
    private CourseService courseService;
    @Resource
    private UserSettingService userSettingService;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private StudentService studentService;
    @Resource
    private StudentRetakeService studentRetakeService;

    @ApiOperation("获取子系统地址")
    @GetMapping("/getSystemUrl")
    public ResponseObject<String> getSystemUrl(@ApiParam(value = "系统id，null获取基础平台地址", required = false) @RequestParam(required = false) String sysId) {
        SubSystemsMainServer subSystemsMainServer = yunBasicService.getSubSystemsMainServer(sysId, false);
        return ResponseObject.ofSuccess(subSystemsMainServer.getWebSvrAddr());
    }

    @ApiOperation("获取基础平台学校历史学期")
    @GetMapping("/getTermInfo/{schoolId}")
    public ResponseObject<List<TermBasicInfo>> getTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.getAllTermInfo(schoolId));
    }

    @ApiOperation("获取当前学期")
    @GetMapping("/getCurrentTermInfo/{schoolId}")
    public ResponseObject<CurrentTermInfo> getCurrentTermInfo(@ApiParam(value = "学校Id", required = true) @PathVariable String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.getCurrentTermInfo(schoolId));
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/getUserDetailInfoByToken")
    public ResponseObject<UserInfo> getUserDetailInfoByToken(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token) {
        //验证token是否有效
        UserInfo userInfo = yunBasicService.getUserInfoByToken(token);
        List<IdentifyType> identityTypeByUserID = yunBasicService.getIdentityTypeByUserID(userInfo.getUserID(), token);
        userInfo.setIdentifyTypes(identityTypeByUserID);
        //存用户第一次登录信息。学生不用保存
        if (!"2".equals(userInfo.getUserType()) && StrUtil.isNotBlank(userInfo.getUserID())) {
            List<UserSetting> list = userSettingService.lambdaQuery().eq(UserSetting::getUserId, userInfo.getUserID()).list();
            if (CollUtil.isEmpty(list)) {
                //获取最新任务
                Optional<TaskInfo> taskInfo = taskInfoService.lambdaQuery().eq(TaskInfo::getSchoolId, userInfo.getSchoolID())
                        .orderByDesc(TaskInfo::getTerm).last("limit 1").oneOpt();
                UserSetting userSetting = new UserSetting();
                userSetting.setUserId(userInfo.getUserID());
                userSetting.setTaskId(taskInfo.isPresent() ? taskInfo.get().getTaskId() : 0);
                userSettingService.save(userSetting);
            }
        }
        return ResponseObject.ofSuccess(userInfo);
    }

    @ApiOperation("获取加密锁信息")
    @GetMapping("/getLockInfo")
    public ResponseObject<LockerInfo> geLockerInfo(@ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        return ResponseObject.ofSuccess(yunBasicService.getSubSystemLockerInfoByID(schoolId));
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public ResponseObject<Integer> logout(@ApiParam(value = "token", required = true) @RequestHeader("Authorization") String token,
                                          @ApiParam(value = "用户id", required = true) @RequestHeader String userId) {
        return ResponseObject.ofSuccess(yunBasicService.logout(userId, token));
    }

    @ApiOperation("同步基础平台教学计划")
    @PostMapping("/syncPlanTeaching")
    public ResponseObject<String> syncPlanTeaching(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                                   @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId,
                                                   @ApiParam(value = "学期", required = true) @RequestParam String term) {
        planTeachingService.syncEducational(taskId, schoolId, term);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("同步基础平台教室")
    @GetMapping("/syncRoom")
    public ResponseObject<String> syncRoom(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                           @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        roomService.syncRoom(taskId, schoolId);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("同步基础平台教室")
    @GetMapping("/syncRoom2")
    public ResponseObject<String> syncRoom2(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                            @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        roomService.syncRoomAdd(taskId, schoolId);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("同步教师")
    @GetMapping("/syncTeacher")
    public ResponseObject<String> syncTeacher(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                              @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        teacherService.syncBaseTeachers(taskId, schoolId);
        return ResponseObject.ofSuccess("同步教师成功");
    }

    @ApiOperation("同步学生")
    @GetMapping("/syncStudent")
    public ResponseObject<String> syncStudent(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                              @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        studentService.syncStudent(taskId, schoolId);
        return ResponseObject.ofSuccess("同步学生成功");
    }

    @ApiOperation("同步课时方案")
    @GetMapping("/syncPeriodScheme")
    public ResponseObject<String> syncPeriodScheme(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                                   @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {

        periodSchemeService.syncPeriodScheme(taskId, schoolId);
        return ResponseObject.ofSuccess("同步课时方案成功");
    }

    @ApiOperation("同步基础平台课程库")
    @GetMapping("/syncCourse")
    public ResponseObject<String> syncCourse(@ApiParam(value = "任务id", required = true) @RequestParam Integer taskId,
                                             @ApiParam(value = "学校Id", required = true) @RequestParam String schoolId) {
        courseService.syncBaseCourse(taskId, schoolId);
        return ResponseObject.ofSuccess();
    }

    @ApiOperation("同步课表至基础平台-课表编排")
    @GetMapping("/syncScheduleToBasic")
    @LogAnnotation(operationType = "13", operationContent = "同步课表至基础平台")
    public ResponseObject syncScheduleToBasic(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                              @ApiParam(value = "用户id", required = true) @RequestHeader String userId,
                                              @ApiParam(value = "用户名字", required = true) @RequestHeader String userName,
                                              @ApiParam(value = "学校id", required = true) @RequestParam String schoolId,
                                              @ApiParam(value = "0：教学班，null：选课", required = true) @RequestParam(required = false) Integer type) {
        return yunBasicService.syncAllScheduleToBasic(taskId, userId, userName, schoolId, type);
    }


    @ApiOperation("同步重修学生")
    @GetMapping("/syncStudentRetake")
    @LogAnnotation(operationType = "13", operationContent = "同步课表至基础平台")
    public ResponseObject syncStudentRetake(@ApiParam(value = "任务id", required = true) @RequestHeader Integer taskId,
                                            @ApiParam(value = "校区id", required = true) @RequestParam String term,
                                            @ApiParam(value = "学校id", required = true) @RequestParam String schoolId) {
        List<Retake> retakes = yunBasicService.syncRetakeStudent(taskId, term, schoolId);
        if (CollUtil.isEmpty(retakes)){
            return ResponseObject.ofFail("没有重修的学生数据");
        }
        return ResponseObject.ofSuccess(studentRetakeService.syncStudentRetake(taskId, schoolId, term, retakes));
    }


}
